import React, { Component } from 'react'
import Header from '../../components/Header/Header'
import Footer from '../../components/Footer/Footer'
import {
  Container, Row, Col, ListGroup, Button, Spinner, Table, Form
} from 'react-bootstrap'
import { connect } from 'react-redux'
import { httpGet, httpPut, httpDelete, httpPost } from '../../services/http'
import CartGoodsItem from './CartGoodsItem/CartGoodsItem'
import intl from 'react-intl-universal'
import './Cart.less'

const formRef = React.createRef()

class Cart extends Component {
  state = { cartGoodsList: [], flag: false }

  async componentDidMount () {
    await this.getCart()
  }

  getCart = async () => {
    const [res, err] = await httpGet({ url: '/cart/getCart' })
    if (res) {
      this.setState({ cartGoodsList: res.data, flag: true })
    } else {
      this.setState({ flag: true })
      console.log(err, '请求失败')
    }
  }

  selectCheck = async (id, checked) => {
    const [res, err] = await httpPut(
      { url: '/cart/setChecked', data: { cid: id, checked } })
    if (res) {
      this.getCart()
    } else {
      console.log('checked修改失败', err)
    }
  }

  handleDeleteMany = async () => {
    const { cartGoodsList } = this.state
    const cid = []
    cartGoodsList.forEach(item => {
      if (item.checked) cid.push(item._id)
    })
    const [res, err] = await httpDelete(
      { url: '/cart/deleteCart', params: { cid } })
    if (res) {
      this.getCart()
    } else {
      console.log('handleDeleteMany报错', err)
    }
  }

  handleAddOrder = async (enTotal, zhTotal) => {
    const { cartGoodsList } = this.state
    const goods = []
    const cid = []
    cartGoodsList.forEach(item => {
      if (item.checked) {
        goods.push({
          detail: item.gid,
          goods_num: item.goods_num,
          zhPrice: item.goods.zhPrice,
          enPrice: item.goods.enPrice,
          zhTitle: item.goods.zhTitle,
          enTitle: item.goods.enTitle,
          img: item.goods.img[0]
        })
        cid.push(item._id)
      }
    })
    console.log(goods, cid)
    const [res, err] = goods.length ? await httpPost({
      url: '/order/addOrder', data: {
        goods, enTotal, zhTotal, cid
      }
    }) : [null, '没有选择物品']
    if (res) {
      console.log('order成功添加', res)
      this.getCart()
    } else {
      console.log('order添加报错', err)
    }
  }

  render () {
    // TODO 这里的总件数和价钱计算的方法不够美观 感觉可以优化一下  感觉是整个cart结构的问题
    const { cartGoodsList, flag } = this.state
    let sumGoodsNum = 0, zhSumPrice = 0, enSumPrice = 0
    cartGoodsList.forEach(item => {
      if (item.checked) {
        sumGoodsNum = sumGoodsNum + item.goods_num
        zhSumPrice = zhSumPrice + item.goods_num * item.goods.zhPrice
        enSumPrice = enSumPrice + item.goods_num * item.goods.enPrice
      }
    })
    intl.load({
      'zh-CN': {
        'enPrice': '' + zhSumPrice
      },
      'en-US': {
        'enPrice': '' + enSumPrice
      }
    })
    return (
      <div id = {'cart'}>
        <Header />
        {
          flag
            ? <Container className = {'main'}>
              <Row style = {{ minHeight: '500px' }}>
                <Col lg = {8}>
                  <h2>
                    {intl.get('cart.title')}
                  </h2>
                  {/* Table的子元素只能是tbody th td td 这样的不能是其他元素,所以将Form放到外面接收多选  */}
                  {
                    cartGoodsList.length ? <Form ref = {formRef}>
                        <Table responsive borderless size = {'sm'}
                               style = {{ minWidth: '650px' }}>
                          <tbody>
                          {
                            cartGoodsList.map((item, index) => {
                              return <CartGoodsItem
                                key = {item._id}
                                onSelectCheck = {this.selectCheck}
                                onGetCart = {this.getCart}
                                item = {item} />
                            })
                          }
                          </tbody>
                        </Table>
                      </Form>
                      : <h3
                        className = {'text-center font-weight-normal'}>
                        {intl.get('nodata')}</h3>
                  }
                </Col>
                <Col lg = {4}>
                  <ListGroup>
                    <ListGroup.Item>
                      <h3>
                        {intl.get('cart.subtotal', { number: sumGoodsNum })}
                      </h3>
                      <p>{intl.get('$') + intl.get('enPrice')}</p>
                    </ListGroup.Item>
                    <ListGroup.Item className = {'clearfix'}>
                      <Button
                        disabled = {!sumGoodsNum}
                        onClick = {() => {
                          this.handleAddOrder(enSumPrice, zhSumPrice)
                        }}
                        style = {{ marginLeft: '20px' }}>
                        {intl.get('cart.buy')}
                      </Button>
                      <Button
                        disabled = {!sumGoodsNum}
                        onClick = {this.handleDeleteMany}
                        style = {{ marginRight: '20px' }}
                        className = {'float-right'}>
                        {intl.get('cart.delete')}
                      </Button>
                    </ListGroup.Item>
                  </ListGroup>
                </Col>
              </Row>
            </Container>
            : <Spinner animation = "border" role = "status" />
        }
        <Footer />
      </div>

    )
  }
}

const mapStateToProps = (state) => {
  return {
    user: state.user
  }
}

export default connect(mapStateToProps)(Cart)
